//app.js
wx.cloud.init();
App({
  setGlobalUser: function(userInfo){
    this.globalData.userInfo = userInfo;
  },
  translateRole: function (role) {
    if (role === 'admin') {
      return '管理员';
    } else if (role === 'vip') {
      return 'VIP用户';
    } else if(!role){
      return '游客';
    }
    return '免费用户';
  },
  translateRoleInContest: function(role){
    if (role === 'host') {
      return '主办方';
    } else if (role === 'singer') {
      return '选手';
    }
    return '观众';
  },
  // 通过云函数获取用户 openid，支持回调或 Promise
  getUserRole: function(nickname) {
    return wx.cloud.callFunction({
      name: 'admin',
      data: {
        action: 'role',
        nickname: nickname
      }
    }).then(res => {
      console.log(res);
      var result = res.result;
      if(!result || result.code !== 20000){
        wx.showToast({
          icon: 'none',
          title: '加载失败，请尝试刷新',
        })
        return 'normal';
      }
      var data = result.data;
      this.globalData.openid = data.openid;
      this.globalData.userrole = data.role;
      this.globalData.nickname = data.nickname;
      return data.role;
    })
  },
  onLaunch: function () {
    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        console.log(res);
      }
    })
  },
  globalData: {
    webprefix: 'https://rouroujiang-2e5v1-1302574543.tcloudbaseapp.com/'
  }
})